/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: KlineFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.ui;

import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bhex.enums.INDEX_TYPE;
import com.bhex.kline.DataHelper;
import com.bhex.kline.KLineChartAdapter;
import com.bhex.kline.KLineChartView;
import com.bhex.kline.KLineEntity;
import com.bhex.kline.KlineKind;
import com.bhex.kline.draw.Status;
import com.bhex.kline.formatter.DateFormatter;
import com.facebook.stetho.common.LogUtil;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.kline.enums.KLINE_BUSI_TYPE;
import io.bhex.app.kline.presenter.KlineFragmentPresenter;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.ShareConfigUtils;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.config.bean.ShareConfigBean;
import io.bhex.sdk.quote.bean.CoinPairBean;


/**
 * ================================================
 * 描   述：K线图
 * ================================================
 */

public class KlineFragment extends BaseFragment<KlineFragmentPresenter,KlineFragmentPresenter.KlineFragmentUI>
        implements KlineFragmentPresenter.KlineFragmentUI{

    public  String MAIN_DRAW = "kind_m_ma";

    public  String SUB_DRAW = "kind_s_macd";

    public static final int KLINE_TYPE_MINUTE = 1;
    public static final int KLINE_TYPE_MINUTE_FIVE = 2;
    public static final int KLINE_TYPE_MINUTE_FIFTEEN = 3;
    public static final int KLINE_TYPE_MINUTE_THIRTY = 4;
    public static final int KLINE_TYPE_HOUR_ONE = 5;
    public static final int KLINE_TYPE_HOUR_FOUR = 10;
    public static final int KLINE_TYPE_DAY_ONE = 6;
    public static final int KLINE_TYPE_WEEK_ONE = 7;
    public static final int KLINE_TYPE_MONTH_ONE = 8;
    public static final int KLINE_TYPE_TIME = 9;
    public KLineChartView chartView;
    private KLineChartAdapter mAdapter;
    //private int currentKlineType=-1;//当前显示的K线类型 默认十五分钟线
    private ImageView waterMarkIcon;

    private boolean isFenshi = false;

    @Override
    protected KlineFragmentPresenter.KlineFragmentUI getUI() {
        return this;
    }

    @Override
    protected KlineFragmentPresenter createPresenter() {
        return new KlineFragmentPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_kline_layout,null,false);
    }

    @Override
    protected void initViews() {
        super.initViews();
        chartView = viewFinder.find(R.id.chartView);
        mAdapter = new KLineChartAdapter();
        chartView.setDateTimeFormatter(new DateFormatter());
        chartView.setAdapter(mAdapter);
        chartView.setGridRows(3);
        //设置副图
        chartView.setChildDraw(Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_SUB).value));
        //设置主图
        Status status = Status.values()[Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_MAIN).value)];
        chartView.changeMainDrawType(status);
        //幅图指标值
        SUB_DRAW = KlineKind.KIND_SUB;
        //主图默认指标
        MAIN_DRAW = KlineKind.KIND_MAIN;

        Bundle arguments = getArguments();
        if (arguments != null) {
            final CoinPairBean coinPairBean = (CoinPairBean) arguments.getSerializable(AppData.INTENT.COINPAIR);
            if(coinPairBean != null && !TextUtils.isEmpty(coinPairBean.getQuotePrecision())) {
                chartView.setValueFormatter(value -> {
                    int priceDigit = NumberUtils.calNumerCount(getContext(), coinPairBean.getMinPricePrecision());
                    return String.format("%."+priceDigit + "f", value);
                });
            }
        }

        //水印logo
        waterMarkIcon = viewFinder.imageView(R.id.icon);
        ShareConfigBean shareConfig = ShareConfigUtils.getShareConfig();
        setWaterMarkIcon(shareConfig);

        chartView.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getPointerCount() > 1||chartView.isLongPress()){
                    if (event.getAction() == MotionEvent.ACTION_UP){
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                    }else{
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                    }
                }
                return false;
            }
        });
    }

    /**
     * 设置水印
     * @param shareConfig
     */
    public void setWaterMarkIcon(ShareConfigBean shareConfig) {
        if (shareConfig != null) {
            String watermarkImageUrl = shareConfig.getWatermarkImageUrl();
            if (!TextUtils.isEmpty(watermarkImageUrl)) {
                chartView.setWaterImageUrl(watermarkImageUrl);
            }

        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();

    }

    /*private void initData() {
        chartView.showLoading();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<KLineEntity> data = DataRequest.getALL(getActivity());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.addFooterData(data);
                        *//*chartView.startAnimation();
                        chartView.refreshEnd();*//*
                    }
                });
            }
        }).start();
    }*/

    @Override
    protected void lazyLoadData() {
        super.lazyLoadData();
    }




    public void setKlineType(int klineType) {
        /*if (currentKlineType!=klineType) {
            if (klineType!=-1 && chartView != null) {
                if( klineType == KLINE_TYPE_TIME)
                    chartView.setLineTime(true);//分时
                else
                    chartView.setLineTime(false);

                //不是首次 切换K线
                switchKlineType(klineType);

            }

            currentKlineType = klineType;
        }*/

    }


    public void switchKlineDraw(int type,String tag){
        if(type==0){
            chartView.hideSelectData();
            chartView.setMainDrawLine(true);
            //chartView.setMainDrawLine(false);
        } else if(tag.equals("kind_m_close")){
            chartView.hideSelectData();
            chartView.changeMainDrawType(Status.NONE);
        }else if(tag.equals("kind_s_close")){
            chartView.hideSelectData();
            chartView.hideChildDraw();
        }else if(tag.endsWith("_macd")){
            chartView.hideSelectData();
            chartView.setChildDraw(Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_SUB).value));
        }else if(tag.endsWith("_kdj")){
            chartView.hideSelectData();
            chartView.setChildDraw(Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_SUB).value));
        }else if(tag.endsWith("_rsi")){
            chartView.hideSelectData();
            chartView.setChildDraw(Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_SUB).value));
        }else if(tag.endsWith("_wr")){
            chartView.hideSelectData();
            chartView.setChildDraw(Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_SUB).value));
        }else if(tag.endsWith("_ma")){
            chartView.hideSelectData();
            chartView.changeMainDrawType(Status.MA);
        }else if(tag.endsWith("_boll")){
            chartView.hideSelectData();
            chartView.changeMainDrawType(Status.BOLL);
        }

        if(tag.startsWith("kind_m_")){
            MAIN_DRAW = tag;
        }else if(tag.startsWith("kind_s_")){
            SUB_DRAW = tag;
        }
    }

    public void switchKlineTypeByString(String type){
        isFenshi = false;
        getPresenter().switchKline(type);
    }

    public void switchTime(String type){
        isFenshi = true;
        getPresenter().switchKline(type);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //chartView.setGridRows(2);
            //chartView.setGridColumns(4);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //chartView.setGridRows(2);
            //chartView.setGridColumns(2);
        }
    }

    @Override
    public void showKline(final List<KLineEntity> datas) {
        chartView.showLoading();
        if(!isVisible() || datas==null || datas.size()==0){
            return;
        }
        DataHelper.calculate(datas);
        getActivity().runOnUiThread(()->{
            if(isFenshi){
                chartView.setMainDrawLine(true);
            }else{
                if(Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_SUB).value)==-1){
                    chartView.hideChildDraw();
                }else{
                    chartView.setChildDraw(Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_SUB).value));
                }
                //设置主图
                Status status = Status.values()[Integer.valueOf(KLINE_BUSI_TYPE.getValue(KlineKind.KIND_MAIN).value)];
                chartView.changeMainDrawType(status);
                chartView.setMainDrawLine(false);
            }
            chartView.setCurrentPrice(datas.get(datas.size()-1).getClosePrice());

            mAdapter.addFooterData(datas);
            mAdapter.notifyDataSetChanged();
            chartView.refreshEnd();
        });
    }

    @Override
    public void updateKlines(List<KLineEntity> addData) {
        if(!isVisible() || addData==null || addData.size()==0){
            return;
        }

        DataHelper.calculate(addData);
        getActivity().runOnUiThread(()->{
            if(isFenshi){
                chartView.setMainDrawLine(true);
            }else{
                chartView.setMainDrawLine(false);
            }
            chartView.setCurrentPrice(addData.get(addData.size()-1).getClosePrice());
            mAdapter.addFooterData(addData);
            mAdapter.notifyDataSetChanged();
            chartView.refreshEnd();
        });
    }

    @Override
    public void updateKline(KLineEntity item) {
        //mAdapter.notifyDataSetChanged();
        //mAdapter.addHeaderData(item);
        chartView.refreshEnd();
    }

    @Override
    public void clearKline() {
        mAdapter.clearData();
    }

    @Override
    public void startRequestKline() {
        chartView.showLoading();
    }

    @Override
    public void completeRequestKline() {
        chartView.refreshComplete();
    }

    /**
     * 切换指标
     * @param index
     */
    public void switchIndex(INDEX_TYPE index) {
        //chartView.switchIndex(index.mName);

    }
}
